import { message } from "antd";
import axios from "axios";
import { getLocale, toApiLanguageCode, tt } from '@/utils/in18';

function normalizeBaseURL(raw?: string) {
  if (!raw) return null;
  const trimmed = raw.trim();
  if (trimmed.startsWith('/')) return trimmed;                         // 相对路径（同源代理，如 /api）
  if (/^https?:\/\//i.test(trimmed)) {                                  // 显式 http/https
    if (window.location.protocol === 'https:' && trimmed.startsWith('http://')) {
      // 前端是 https，强制把后端也升级为 https，避免混合内容被浏览器拦截
      return 'https://' + trimmed.slice(7);
    }
    return trimmed;
  }
  if (trimmed.startsWith('//')) {                                       // 协议相对
    return window.location.protocol + trimmed;
  }
  // 纯主机名，补全协议
  return `${window.location.protocol}//${trimmed}`;
}

const resolvedEnv = normalizeBaseURL(import.meta.env.VITE_API as any);
const BASE_URL = resolvedEnv || `${window.location.origin}/api`;         // 未配置则默认同源 /api

export const request = axios.create({
  baseURL: BASE_URL,
  timeout: 60000,
  withCredentials: true,                                                 // 关键：携带跨站 Cookie
  headers: { 'X-Requested-With': 'XMLHttpRequest' },
});

request.interceptors.request.use((config) => {
  try {
    if (!config.headers) config.headers = {} as any;
    const headersObj: any = config.headers;
    const commonObj: any = headersObj.common || {};
    const hasAuthHeader =
      ['Authorization', 'authorization'].some((k) => typeof headersObj[k] !== 'undefined') ||
      ['Authorization', 'authorization'].some((k) => typeof commonObj[k] !== 'undefined');

    if (!hasAuthHeader) {
      let tokenFromUserData: string | null = null;
      try {
        const raw = localStorage.getItem('userData');
        if (raw) {
          const parsed = JSON.parse(raw);
          tokenFromUserData = parsed?.user_token ?? null;
        }
      } catch {}
      const legacyToken = localStorage.getItem('token');
      const defaultToken = tokenFromUserData || legacyToken;
      if (defaultToken) {
        // 服务器通常期望 `Authorization: Bearer <token>`，确保前缀存在
        const bearerToken = typeof defaultToken === 'string' && defaultToken.startsWith('Bearer ') ? defaultToken : `Bearer ${defaultToken}`;
        headersObj['Authorization'] = bearerToken;
        if (headersObj.common) headersObj.common['Authorization'] = bearerToken;
      }
    }
  } catch {}

  // 统一添加语言参数，兼容 FormData/URLSearchParams，避免破坏 multipart/form-data
  try {
    const locale = getLocale();
    const lang = toApiLanguageCode(locale as any);
    const method = (config.method || '').toLowerCase();
    if (method === 'post' || method === 'put' || method === 'patch') {
      const payload: any = config.data;
      if (payload instanceof FormData) {
        if (!payload.has('language')) payload.append('language', lang);
      } else if (typeof URLSearchParams !== 'undefined' && payload instanceof URLSearchParams) {
        if (!payload.has('language')) payload.set('language', lang);
      } else if (payload && typeof payload === 'object') {
        config.data = { language: lang, ...payload };
      } else {
        config.data = { language: lang };
      }
    } else {
      config.params = { ...(config.params || {}), language: lang };
    }
  } catch {}

  // 确保跨域时也带上凭证（某些 axios 调用场景会覆盖实例级配置）
  (config as any).withCredentials = true;

  return config;
});

request.interceptors.response.use(
  (response) => response,
  (error) => {
    try {
      // 区分网络层/CORS/被 VPN 或浏览器拦截 的场景
      if (!error || !error.response || error.response.status === 0 || error.message === 'Network Error') {
        message.error(tt('home.network_unreachable'));
      } else if (error.response?.data?.message) {
        message.error(error.response.data.message);
      } else {
        message.error(tt('home.request_failed_try_again'));
      }
    } catch {}
    return Promise.reject(error);
  }
);